package cn.itcast.bos.service.system.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.system.MenuRepository;
import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.MenuService;

@Service
@Transactional
public class MenuServiceImpl implements MenuService {

	@Autowired
	private MenuRepository menuRepository;

	@Override
	public List<Menu> findAll() {
		return menuRepository.findAll();
	}

	@Override
	public void save(Menu menu) {

		// 业务层执行保存添加菜单项的操作
		// 该菜单对象关联了一个父菜单项,需要对父菜单项的id进行判断(当不关联府菜单项时,父菜单项不为null,而其id为null)
		if (menu.getParentMenu() != null && menu.getParentMenu().getId() == null
				|| menu.getParentMenu().getId() == 0) {
			//此时没有关联父菜单项,所以需要将府菜单项置为null
			menu.setParentMenu(null);
		}
		//执行保存的操作
		menuRepository.save(menu);
	}

	@Override
	public List<Menu> findByUser(User user) {
		//针对"admin"用户返回全部的菜单项
		if("admin".equals(user.getUsername())) {
			return menuRepository.findAll();
		}else {
			return menuRepository.findByUser(user.getId());
		}
	}

}
